<script setup lang="ts">
import type { AppointmentRecord } from '@shared/types/'
import { Delete, Download, Refresh, Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'

const loading = ref(false)
const records = ref<AppointmentRecord[]>([])
const selectedRecord = ref<AppointmentRecord | null>(null)
const detailDialogVisible = ref(false)
const dateRange = ref<[string, string] | null>(null)

// 筛选条件
const filters = reactive({
  status: '',
  search: '',
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0,
})

// 排序
const sort = reactive({
  field: 'created_at',
  order: 'desc',
})

// 方法
function getStatusTagType(status: string) {
  switch (status) {
    case 'confirmed': return 'success'
    case 'pending': return 'warning'
    case 'cancelled': return 'info'
    case 'failed': return 'danger'
    default: return ''
  }
}

function getStatusText(status: string) {
  const statusMap: Record<string, string> = {
    pending: '等待中',
    confirmed: '已确认',
    cancelled: '已取消',
    failed: '失败',
  }
  return statusMap[status] || status
}

function getModeText(mode: string) {
  const modeMap: Record<string, string> = {
    standard: '标准',
    quick: '快速',
    batch: '批量',
    monitor: '监控',
  }
  return modeMap[mode] || mode
}

function formatAppointmentDate(val?: string) {
  if (!val)
    return ''
  const s = String(val)
  if (/^\d{2}-\d{2}-\d{4}$/.test(s)) {
    const [dd, mm, yyyy] = s.split('-')
    return `${yyyy}-${mm}-${dd}`
  }
  return s
}

function formatTime(timestamp: number) {
  if (typeof timestamp !== 'number' || !Number.isFinite(timestamp))
    return '-'
  return dayjs(timestamp * 1000).format('YYYY-MM-DD HH:mm:ss')
}

function formatBytes(n?: number) {
  if (typeof n !== 'number' || !Number.isFinite(n))
    return '-'
  if (n < 1024)
    return `${n} B`
  const kb = n / 1024
  if (kb < 1024)
    return `${kb.toFixed(1)} KB`
  const mb = kb / 1024
  if (mb < 1024)
    return `${mb.toFixed(2)} MB`
  const gb = mb / 1024
  return `${gb.toFixed(2)} GB`
}

function formatMs(ms?: number) {
  if (typeof ms !== 'number' || !Number.isFinite(ms))
    return '-'
  if (ms < 1000)
    return `${ms} ms`
  const s = ms / 1000
  if (s < 60)
    return `${s.toFixed(2)} s`
  const m = Math.floor(s / 60)
  const sec = Math.floor(s % 60)
  return `${m}m ${sec}s`
}

async function loadRecords() {
  try {
    loading.value = true

    // 构建筛选条件
    const requestFilters: any = {}

    if (filters.status) {
      requestFilters.status = filters.status
    }

    if (dateRange.value) {
      requestFilters.date_range = {
        start: dateRange.value[0],
        end: dateRange.value[1],
      }
    }

    if (filters.search) {
      requestFilters.user_info = {
        passport_number: filters.search,
        license_owner_name: filters.search,
      }
    }

    const result = await window.api.db.appointments.list({
      filters: requestFilters,
      pagination: {
        offset: (pagination.page - 1) * pagination.size,
        limit: pagination.size,
      },
      sort: {
        field: sort.field,
        order: sort.order as 'asc' | 'desc',
      },
    })

    if (result.success) {
      records.value = result.data.appointments
      pagination.total = result.data.total
    }
    else {
      throw new Error(result.error || '加载记录失败')
    }
  }
  catch (error) {
    console.error('加载预约记录失败:', error)
    ElMessage.error('加载记录失败')
  }
  finally {
    loading.value = false
  }
}

function handleSortChange({ prop, order }: any) {
  if (prop && order) {
    sort.field = prop
    sort.order = order === 'ascending' ? 'asc' : 'desc'
    loadRecords()
  }
}

function viewRecord(record: AppointmentRecord) {
  selectedRecord.value = record
  detailDialogVisible.value = true
}

async function deleteRecord(record: AppointmentRecord) {
  try {
    await ElMessageBox.confirm(`确定要删除记录 ${record.id} 吗？`, '确认删除', {
      type: 'warning',
    })

    const result = await window.api.db.appointments.delete(record.id)

    if (result.success) {
      ElMessage.success('记录已删除')
      await loadRecords()
    }
    else {
      throw new Error('删除失败')
    }
  }
  catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败:', error)
      ElMessage.error('删除记录失败')
    }
  }
}

async function exportRecords() {
  try {
    const result = await window.api.db.appointments.export({
      format: 'csv',
      filters: {
        status: filters.status,
        date_range: dateRange.value
          ? {
              start: dateRange.value[0],
              end: dateRange.value[1],
            }
          : undefined,
      },
    })

    if (result.success) {
      ElMessage.success(`导出完成，共 ${result.record_count} 条记录`)
      // 可选：打开文件所在目录
      await window.api.system.showInFolder(result.file_path)
    }
    else {
      throw new Error(result.error || '导出失败')
    }
  }
  catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出失败')
  }
}

async function clearRecords() {
  try {
    await ElMessageBox.confirm('确定要清空所有预约记录吗？此操作不可撤销。', '确认清空', {
      type: 'warning',
    })

    // TODO: 实现清空记录功能
    ElMessage.info('清空功能开发中...')
  }
  catch {
    // 用户取消
  }
}

// 监听筛选条件变化
watch([filters, dateRange], () => {
  pagination.page = 1 // 重置到第一页
  loadRecords()
}, { deep: true })

// 生命周期
onMounted(() => {
  loadRecords()
})
</script>

<template>
  <div class="records-page">
    <div class="mb-6">
      <h2 class="mb-2 text-2xl text-gray-800 font-bold">
        预约记录
      </h2>
      <p class="text-gray-600">
        查看和管理所有预约记录
      </p>
    </div>

    <!-- 筛选和操作栏 -->
    <div class="card mb-6">
      <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <!-- 筛选条件 -->
        <div class="flex flex-wrap items-center gap-4">
          <el-select
            v-model="filters.status"
            placeholder="状态筛选"
            clearable
            style="width: 120px"
          >
            <el-option label="等待中" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="失败" value="failed" />
          </el-select>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />

          <el-input
            v-model="filters.search"
            placeholder="搜索护照号或姓名"
            style="width: 200px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-button @click="loadRecords">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center gap-2">
          <el-button @click="exportRecords">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
          <el-button type="danger" @click="clearRecords">
            <el-icon><Delete /></el-icon>
            清空记录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 记录表格 -->
    <div class="card">
      <el-table
        v-loading="loading"
        :data="records"
        stripe
        class="w-full"
        empty-text="暂无预约记录"
        @sort-change="handleSortChange"
      >
        <el-table-column label="ID" prop="id" width="80" sortable="custom" />

        <el-table-column label="参考编号" width="120">
          <template #default="{ row }">
            <code v-if="row.reference_number" class="text-sm">{{ row.reference_number }}</code>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div>
              <div class="font-medium">
                {{ row.user_name }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.user_passport }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.user_email }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="预约信息" min-width="180">
          <template #default="{ row }">
            <div>
              <div class="font-medium">
                {{ formatAppointmentDate(row.appointment_date) }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.appointment_time }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.office_code }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="预约模式" width="100">
          <template #default="{ row }">
            <el-tag size="small" type="info">
              {{ getModeText(row.booking_mode) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="耗时" width="120">
          <template #default="{ row }">
            {{ formatMs((row as any).duration_ms) }}
          </template>
        </el-table-column>

        <el-table-column label="流量(出/入)" min-width="160">
          <template #default="{ row }">
            <div class="text-sm text-gray-700">
              {{ formatBytes((row as any).traffic_bytes_sent) }} / {{ formatBytes((row as any).traffic_bytes_received) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="总流量(计费)" width="140">
          <template #default="{ row }">
            {{ formatBytes(((row as any).traffic_bytes_sent || 0) + ((row as any).traffic_bytes_received || 0)) }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160" sortable="custom" prop="created_at">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="flex space-x-1">
              <el-button
                size="small"
                @click="viewRecord(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteRecord(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadRecords"
          @size-change="loadRecords"
        />
      </div>
    </div>

    <!-- 记录详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约记录详情"
      width="600px"
    >
      <div v-if="selectedRecord" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="text-sm text-gray-600 font-medium">记录ID</label>
            <div class="mt-1">
              {{ selectedRecord.id }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">参考编号</label>
            <div class="mt-1">
              {{ selectedRecord.reference_number || '-' }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">护照号码</label>
            <div class="mt-1">
              {{ selectedRecord.user_passport }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">驾照号码</label>
            <div class="mt-1">
              {{ selectedRecord.user_license }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">姓名</label>
            <div class="mt-1">
              {{ selectedRecord.user_name }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">邮箱</label>
            <div class="mt-1">
              {{ selectedRecord.user_email }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">电话</label>
            <div class="mt-1">
              {{ selectedRecord.user_phone || '-' }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">签发国家</label>
            <div class="mt-1">
              {{ selectedRecord.issuing_country }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">签发机关</label>
            <div class="mt-1">
              {{ selectedRecord.issuing_authority }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">服务类型</label>
            <div class="mt-1">
              {{ selectedRecord.service_type }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">办理地点</label>
            <div class="mt-1">
              {{ selectedRecord.office_code }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">预约日期</label>
            <div class="mt-1">
              {{ selectedRecord.appointment_date }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">预约时间</label>
            <div class="mt-1">
              {{ selectedRecord.appointment_time }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">状态</label>
            <div class="mt-1">
              <el-tag :type="getStatusTagType(selectedRecord.status)">
                {{ getStatusText(selectedRecord.status) }}
              </el-tag>
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">预约模式</label>
            <div class="mt-1">
              {{ getModeText(selectedRecord.booking_mode) }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">创建时间</label>
            <div class="mt-1">
              {{ formatTime(selectedRecord.created_at) }}
            </div>
          </div>

          <div>
            <label class="text-sm text-gray-600 font-medium">耗时</label>
            <div class="mt-1">
              {{ formatMs((selectedRecord as any).duration_ms) }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">流量(出/入)</label>
            <div class="mt-1">
              {{ formatBytes((selectedRecord as any).traffic_bytes_sent) }} / {{ formatBytes((selectedRecord as any).traffic_bytes_received) }}
            </div>
          </div>
          <div>
            <label class="text-sm text-gray-600 font-medium">总流量（计费）</label>
            <div class="mt-1">
              {{ formatBytes(((selectedRecord as any).traffic_bytes_sent || 0) + ((selectedRecord as any).traffic_bytes_received || 0)) }}
              <span class="text-xs text-gray-500">= 出 + 入</span>
            </div>
          </div>
        </div>

        <div v-if="selectedRecord.error_message">
          <label class="text-sm text-gray-600 font-medium">错误信息</label>
          <div class="mt-1 border border-red-200 rounded bg-red-50 p-3 text-sm text-red-700">
            {{ selectedRecord.error_message }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.records-page {
  max-width: 1400px;
}

.grid {
  display: grid;
  gap: 1rem;
}

.grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
</style>
